<template>
  <div class="login-container">
    <el-card class="box-card">
      <div class="head"></div>
      <el-form ref="form" :model="user" :rules="rules">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            v-model="user.username"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            type="password"
            placeholder="请输入密码"
            show-password
            prefix-icon="el-icon-lock"
            v-model="user.password"
          ></el-input>
        </el-form-item>
        <!-- 按钮登录 -->
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
      <el-link :underline="false" @click="$router.push('/reg')">还没有账号，去注册</el-link>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'MyLogin',
  data() {
    return {
      user: {
        username: '',
        password: ''
      },
      rules: {
        // 验证用户名的规则
        username: [
          // required: true 表示必填；  trigger: blur 表示失去焦点时触发
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        // 验证密码的规则
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // console.log('通过')
        const { data: res } = await loginAPI(this.user)
        // console.log(res)
        if (res.code === 0) {
          this.$message.success(res.message)
          this.$store.commit('user/updateToken', res.token)
          this.$router.push('/home')
        } else {
          this.$message.error(res.message)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  background: url(@/assets/images/login_bg.jpg) no-repeat;
  height: 100%;
  background-size: cover;
}

.el-card {
  width: 400px;
  height: 310px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  .head {
    height: 40px;
    background: url(@/assets/images/login_title.png) no-repeat top center;
  }
  .el-button {
    width: 100%;
  }
}
</style>
